package com.starter.jienlee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.starter.jienlee.common.exception.BusinessException;
import com.starter.jienlee.common.param.LoginRegisterParam;
import com.starter.jienlee.entity.UserUser;
import com.starter.jienlee.enums.RestCodeEnum;
import com.starter.jienlee.enums.StatusEnums;
import com.starter.jienlee.utils.AssertUtil;
import com.starter.jienlee.utils.EncryptUtil;
import com.starter.jienlee.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.starter.jienlee.dao.mapper.UserUserMapper;

import com.starter.jienlee.service.UserUserService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserUserServiceImpl extends ServiceImpl<UserUserMapper, UserUser> implements UserUserService{

    @Override
    public Map doLogin(LoginRegisterParam loginRegisterParam) {
        UserUser user = getByAccount(loginRegisterParam.getAccount());
        AssertUtil.nonNull(user, BusinessException.of(RestCodeEnum.USER_ACCOUNT_NOT_FIND));
        if (!StringUtils.equals(user.getPassword(), EncryptUtil.toMD5(loginRegisterParam.getPassword()))) {
            throw BusinessException.of(RestCodeEnum.USER_PASSWORD_NOT_CORRECT);
        }
        if (StatusEnums.locking.getKey() == user.getEnabled().intValue()) {
            throw BusinessException.of(RestCodeEnum.USER_STATUS_IS_BLOCK);
        }
        Map<String, String> claims = new HashMap<>();
        claims.put("id", user.getId().toString());
        String token = JwtUtil.genToken(claims);

        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        result.put("nickName", user.getNickName());
        return result;
    }

    @Override
    public void toRegister(LoginRegisterParam loginRegisterParam) {
        UserUser oldUser = getByAccount(loginRegisterParam.getAccount());
        AssertUtil.isNull(oldUser, BusinessException.of(RestCodeEnum.USER_ACCOUNT_IS_EXIST));
        Date date = new Date();
        UserUser user = UserUser.builder()
                .account(loginRegisterParam.getAccount())
                .email(loginRegisterParam.getAccount())
                .password(EncryptUtil.toMD5(loginRegisterParam.getPassword()))
                .createTime(date)
                .updateTime(date)
                .enabled(StatusEnums.StatusEnums.getKey()).build();
        baseMapper.insert(user);
    }

    public UserUser getByAccount(String account) {
        LambdaQueryWrapper<UserUser> queryWrapper = new QueryWrapper<UserUser>().lambda()
                .eq(UserUser::getAccount, account);
        return baseMapper.selectOne(queryWrapper);
    }
}
